var express = require('express');
var router = express.Router();
var {
    qfuser_model,
    qfanno_model
} = require("../utils/model");
var {
    createToken,
    checkToken
} = require("../utils/token")
router.get('/test', function (req, res) {
    res.send("API - API  - TEST ")
})

var axios = require("axios")
var multer = require("multer")
//测试接口
router.get('/index', (req, res) => {
    res.json({
        code: 200,
        msg: '测试成功',
        result: null
    })
})



//删除公告
router.post('/deleteanno', (req, res) => {
    var body = req.body
    checkToken(req, res, ({
        username
    }) => {
        qfanno_model.remove({
                _id: body._id
            })
            .then(result => {
                res.json({
                    code: 200,
                    msg: '删除成功',
                    result
                })
            })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: "服务器异常",
                    err
                })
            })
    })
})


//公告列表
router.post("/getnoticelist", (req, res) => {
    var {keyword,type} = req.body; 
    var obj = {}
    if(keyword||type||type==0){
      obj = {
        $or:[
          {
            context:new RegExp(keyword),
          },
          {
            time:new RegExp(keyword)
          }
        ],
        type:type
      }
    }

    checkToken(req, res, ({
        phone
    }) => {
        qfanno_model.find(obj, {})
            .sort({
                _id: -1
            })
            .then(result => {

                res.json({
                    code: 200,
                    msg: "查询成功",
                    result
                })
            })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: "服务器异常",
                    err
                })
            })
    })
})

//添加公告
router.post("/addanno", (req, res) => {
    var body = req.body;
    // 直接插入
    body.time = new Date()
    qfanno_model.insertMany(body)
        .then(result => {
            res.json({
                code: 200,
                msg: "公告添加成功!",
                result
            })
        })
        .catch(err => {
            res.json({
                code: 500,
                msg: "服务器异常",
                err
            })
        })
})


//用户修改权限
router.post('/setuserrole', (req, res) => {
    var body = req.body
    checkToken(req, res, ({
        username
    }) => {
        qfuser_model.updateMany({
                _id: body._id
            }, {
                $set: {
                    role: body.role
                }
            })
            .then(result => {
                res.json({
                    code: 200,
                    msg: '修改成功',
                    result
                })
            })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: "服务器异常",
                    err
                })
            })
    })
})


//用户删除
router.post('/deleteuser', (req, res) => {
    var body = req.body
    checkToken(req, res, ({
        username
    }) => {
        qfuser_model.remove({
                _id: body._id
            })
            .then(result => {
                res.json({
                    code: 200,
                    msg: '删除成功',
                    result
                })
            })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: "服务器异常",
                    err
                })
            })
    })
})



//用户列表
router.post('/getuserlist', (req, res) => {
    var {keyword,role} = req.body; 
    var obj = {}
    if(keyword||role||role==0){
      obj = {
        $or:[
          {
            username:new RegExp(keyword),
          },
          {
            phone:new RegExp(keyword)
          }
        ],
        role:role
      }
    }

    checkToken(req, res, ({
        username
    }) => {
        qfuser_model.find(obj).sort({
                role: 1,
                _id: -1
            })
            .then(result => {
                res.json({
                    code: 200,
                    msg: '查询成功',
                    result
                })
            })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: "服务器异常",
                    err
                })
            })
    })
})

//修改个人信息（头像）
router.post("/changeinfo", (req, res) => {
    var body = req.body;
    checkToken(req, res, ({
        username
    }) => {
        qfuser_model.updateMany({
                username
            }, {
                $set: {
                    avatar: body.avatar
                }
            })
            .then(result => {
                res.json({
                    code: 200,
                    msg: "修改成功",
                    result: result
                })
            })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: "服务器异常",
                    err
                })
            })
    })
})



// 上传头像
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images/uploads')
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)

        cb(null, "WH2110_" + new Date().getTime() + "_" + file.originalname) // photo.png => wh2110photo.122312124123.png  文件名冲突  
    }
})

const upload = multer({
    storage: storage
}).any()


// 上传文件
router.post("/uploadfile", upload, (req, res) => {
    checkToken(req, res, ({
        username
    }) => {
        console.log(req.files)
        var file = req.files[0]
        res.json({
            code: 200,
            msg: "上传成功",
            path: file.path, // 上传成功的相对于服务器的路径  
            result: file.path
        })
    })
})

//修改密码
router.post("/changepass", (req, res) => {
    var body = req.body
    checkToken(req, res, ({
        username
    }) => {
        qfuser_model.findOne({
                username
            })
            .then(result => {
                if (result.password == body.oldpass) {
                    qfuser_model.updateMany({
                            username
                        }, {
                            $set: {
                                password: body.newpass
                            }
                        })
                        .then(result => {
                            res.json({
                                code: 200,
                                msg: "密码修改成功,请重新登录",
                                result
                            })
                        })
                } else {
                    res.json({
                        code: 401,
                        msg: "原始密码错误",
                    })
                }
            })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: "服务器异常",
                    err
                })
            })
    })
})
//验证验证码
router.post('/verifycaptcha', (req, res) => {
    let body = req.body
    // console.log(body);
    qfuser_model.findOne({
            phone: body.phone
        })
        .then(value => {
            if (value) {
                axios.get("http://47.104.209.44:3333/captcha/verify", {
                        params: body
                    })
                    .then(result => {
                        // result.data.code==200
                        if (result.data.code == 200) {
                            var token = createToken({
                                phone: value.phone,
                                username: value.username
                            })
                            res.json({
                                code: 200,
                                msg: '登录成功',
                                result: result.data,
                                token
                            })
                        } else {
                            res.json({
                                code: 401,
                                msg: '登录失败',
                                result: result.data
                            })
                        }
                    })
            } else {
                res.json({
                    code: 401,
                    msg: '当前手机号还未注册,无法发送验证码',

                })
            }
        })
        .catch(err => {
            res.json({
                code: 500,
                msg: "服务器异常",
                err
            })
        })
})

//发送验证码
router.post('/sendcaptcha', (req, res) => {
    let body = req.body
    console.log(body);

    qfuser_model.findOne({
            phone: body.phone
        })
        .then(result => {
            // console.log(result);

            if (result) {
                axios.get("http://47.104.209.44:3333/captcha/sent", {
                        params: {
                            phone: body.phone
                        }
                    })
                    .then(result => {
                        // result.data.code==200
                        if (result.data.code == 200) {
                            res.json({
                                code: 200,
                                msg: '发送成功',
                                result: result.data
                            })
                        } else {
                            res.json({
                                code: 401,
                                msg: '手机号不存在，发送失败',
                                result: result.data
                            })
                        }
                    })
            } else {
                res.json({
                    code: 401,
                    msg: '当前手机号还未注册,无法发送验证码',

                })
            }
        })
        .catch(err => {
            res.json({
                code: 500,
                msg: "服务器异常",
                err
            })
        })
})
// 注册
router.post("/register", (req, res) => {
    var body = req.body;
    qfuser_model.findOne({
            $or: [{
                    username: body.username
                },
                {
                    phone: body.phone
                }
            ]
        })
        .then(data => {
            if (data) {
                res.json({
                    code: 3001,
                    msg: "当前用户已经被注册",
                    result: data
                })
            } else {
                // 直接插入
                body.time = new Date()
                qfuser_model.insertMany(body)
                    .then(result => {
                        res.json({
                            code: 200,
                            msg: "注册成功!",
                            result
                        })
                    })
            }
        })
        .catch(err => {
            res.json({
                code: 500,
                msg: "服务器异常",
                err
            })
        })
})

// 登录
router.post("/loginusername", (req, res) => {
    var body = req.body;
    qfuser_model.findOne({
            username: body.username
        })
        .then(data => {
            if (data) {
                if (data.password == body.password) {
                    // 生成 token 
                    const token = createToken({
                        username: data.username,
                        phone: data.phone,
                        password: data.password
                    })
                    res.json({
                        code: 200,
                        msg: "登录成功",
                        result: data,
                        token
                    })
                } else {
                    res.json({
                        code: 401,
                        msg: "用户名和密码不匹配,登录失败",
                    })
                }
            } else {
                res.json({
                    code: 401,
                    msg: "用户名不存在,登录失败",
                })
            }
        })
        .catch(err => {
            res.json({
                code: 500,
                msg: "服务器异常",
                err
            })
        })
})

//获取用户信息
router.post('/getuserinfo', (req, res) => {
    checkToken(req, res, ({
        username
    }) => {
        qfuser_model.findOne({
                username
            }).then(result => {
                res.json({
                    code: 200,
                    msg: "获取个人信息成功",
                    result
                })
            })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: "服务器异常",
                    err
                })
            })
    })
})
module.exports = router;